module TLC_DA(    //输入数字量转换为模拟量模块，本实验用TLC5620 
//端口信号：模块的输入输出接口
	input         clk,   //系统时钟50MHz 
	input         rst_n, //低电平复位
	input [10:0]  data_in, //输入一帧数据	
	output     	  da_data, //串行数据接口
	output    	  da_clk,  //串行时钟接口     
	output reg    da_ldac, //更新控制信号
	output reg 	  da_load  //串行加载控制接口
	);

	//计数器时钟分频：根据芯片内部的时序要求进行分频
	reg [30:0] cnt;
	wire       da_clk_r;  //TLC 5620内部时钟信号
	always@(posedge clk or negedge rst_n)  //满足协议中的时钟要求，在TLC 5620中时钟要求不大于1MHZ
		if(!rst_n)
			cnt  <= 6'd0;
		else	
			cnt <= cnt + 1'b1;
			
	assign da_clk_r = cnt[5];
			
	//接收时序状态机		
	reg [2:0]  state;
	reg [3:0]  cnt_da;
	reg        da_data_r;
	reg        da_data_en;  //限定da_data,da_clk的有效区域
	always@(posedge da_clk_r or negedge rst_n)
		if(!rst_n)
			begin
				state <= 0;
				cnt_da <= 0;
				da_load <= 1;
				da_ldac <= 0;			
				da_data_r <= 1'b1;
				da_data_en <= 0;
			end
		else
			case(state)
				0: state <= 1;
				1: begin
					da_load <= 1;
					da_data_en <= 1;
						if(cnt_da <= 10)
							begin
								cnt_da <= cnt_da + 1'b1;
								case(cnt_da)
									0:  da_data_r <= data_in[10];
									1:  da_data_r <= data_in[9];
									2:  da_data_r <= data_in[8];
									3:  da_data_r <= data_in[7];
									4:  da_data_r <= data_in[6];
									5:  da_data_r <= data_in[5];
									6:  da_data_r <= data_in[4];
									7:  da_data_r <= data_in[3];
									8:  da_data_r <= data_in[2];
									9:  da_data_r <= data_in[1];
									10: da_data_r <= data_in[0];
									default:;
								endcase
								state <= 1;
							end
						else
							begin
								cnt_da <= 0;
								state <= 2;
								da_data_en <= 0;
							end
					end
				2: begin
						da_load <= 0;
						state <= 3;
					end
				3: begin
						da_load <= 1;
						state <= 0;
					end
				default: state <= 0;
			endcase

	assign da_data = (da_data_en) ? da_data_r : 1'b1;
	assign da_clk  = (da_data_en)?da_clk_r : 1'b0;

endmodule	